package com.sinochem.yunlian.ship.base.rpc;

import com.sinochem.yunlian.ship.api.vo.bs.CityVo;
import com.sinochem.yunlian.ship.base.biz.BsCityBiz;
import com.sinochem.yunlian.ship.base.entity.BsCity;
import com.sinochem.yunlian.ship.common.annotation.IgnoreToken;
import com.sinochem.yunlian.ship.common.constant.RedisKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jayway on 2017/12/19.
 */
@IgnoreToken
@RestController
@RequestMapping("/api/city")
public class BsCityRest {

    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    private BsCityBiz bsCityBiz;



    @RequestMapping(value = "/findCityByAreaId", method = RequestMethod.GET)
    public CityVo findByPortId(@RequestParam("areaId") Long areaId) {
        if (redisTemplate.hasKey(RedisKey.KEY_CITY_MAP)) {
            Map<String,CityVo> resultMap = redisTemplate.opsForHash().entries(RedisKey.KEY_CITY_MAP);
            return resultMap.get(areaId);
        } else {
            List<BsCity> list = bsCityBiz.findAllCitys();
            Map<String,CityVo> cityMap = new HashMap<>(list.size());
            for (BsCity city : list) {
                CityVo vo = new CityVo();
                vo.setId(city.getId());
                vo.setAreaId(city.getAreaId());
                vo.setAreaName(city.getAreaName());
                vo.setParentId(vo.getParentId());
                cityMap.put(vo.getAreaId(),vo);
            }
            redisTemplate.opsForHash().putAll(RedisKey.KEY_CITY_MAP,cityMap);
            return cityMap.get(areaId);
        }
    }

    @RequestMapping(value = "/findCityNameByAreaId", method = RequestMethod.GET)
    public String findCityNameByPortId(@RequestParam("areaId") Long areaId) {
        if (redisTemplate.hasKey(RedisKey.KEY_CITY_MAP)) {
            Map<String,CityVo> resultMap = redisTemplate.opsForHash().entries(RedisKey.KEY_CITY_MAP);
            CityVo resultVo = resultMap.get(areaId+"");
            return resultVo.getAreaName();
        } else {
            List<BsCity> list = bsCityBiz.findAllCitys();
            Map<String,CityVo> cityMap = new HashMap<>(list.size());
            for (BsCity city : list) {
                CityVo vo = new CityVo();
                vo.setId(city.getId());
                vo.setAreaId(city.getAreaId());
                vo.setAreaName(city.getAreaName());
                vo.setParentId(vo.getParentId());
                cityMap.put(vo.getAreaId(),vo);
            }
            redisTemplate.opsForHash().putAll(RedisKey.KEY_CITY_MAP,cityMap);
            CityVo resultVo = cityMap.get(areaId+"");
            return resultVo.getAreaName();
        }
    }
}
